﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace EasoScreen.Plugins;
public class XmlEditor
{

    public void AddTask(TaskTemplate taskTemplate)
    {
        XmlDocument xmlDocument = new XmlDocument();
        xmlDocument.Load("ScheduleData.xml");
        XmlElement root = xmlDocument.DocumentElement;
        XmlNode taskNode = xmlDocument.CreateElement("Task");
        taskNode.Attributes.Append(xmlDocument.CreateAttribute("Name")).Value = taskTemplate.Name;
        taskNode.Attributes.Append(xmlDocument.CreateAttribute("Time")).Value = taskTemplate.Time;
        taskNode.Attributes.Append(xmlDocument.CreateAttribute("Date")).Value = taskTemplate.Date;
        root.AppendChild(taskNode);
        xmlDocument.Save("ScheduleData.xml");
    }
    public TaskTemplate GetLatestTask()
    {
        XmlDocument xmlDocument = new XmlDocument();
        xmlDocument.Load("ScheduleData.xml");
        TaskTemplate taskTemplate = new TaskTemplate();
        taskTemplate.Name = xmlDocument.SelectSingleNode("/ScheduleData/Task").Attributes["Name"].Value;
        taskTemplate.Time = xmlDocument.SelectSingleNode("/ScheduleData/Task").Attributes["Time"].Value;
        taskTemplate.Date = xmlDocument.SelectSingleNode("/ScheduleData/Task").Attributes["Date"].Value;
        return taskTemplate;
    }
    public void DeleteLatestTask()
    {
        XmlDocument xmlDocument = new XmlDocument();
        xmlDocument.Load("ScheduleData.xml");
        XmlNode taskNode = xmlDocument.SelectSingleNode("/ScheduleData/Task");
        if (taskNode != null)
        {
            xmlDocument.DocumentElement.RemoveChild(taskNode);
            xmlDocument.Save("ScheduleData.xml");
        }
    }
    public void SortTasksByDate()
    {
        XmlDocument xmlDocument = new XmlDocument();
        xmlDocument.Load("ScheduleData.xml");
        XmlNodeList taskNodes = xmlDocument.SelectNodes("/ScheduleData/Task");
        List<XmlNode> taskList = taskNodes.Cast<XmlNode>().ToList();
        
        taskList.Sort((x, y) => DateTime.Compare(
            DateTime.ParseExact(x.Attributes["Date"].Value + "/" + x.Attributes["Time"].Value.Substring(x.Attributes["Time"].Value.IndexOf("-") + 1), "yyyy/MM/dd/HH:mm", null),
            DateTime.ParseExact(y.Attributes["Date"].Value + "/" + y.Attributes["Time"].Value.Substring(y.Attributes["Time"].Value.IndexOf("-") + 1), "yyyy/MM/dd/HH:mm", null)
        ));
        XmlElement root = xmlDocument.DocumentElement;
        root.RemoveAll();
        foreach (var task in taskList)
        {
            root.AppendChild(xmlDocument.ImportNode(task, true));
        }
        
        xmlDocument.Save("ScheduleData.xml");
    }
}
